package algorithm.tree.binarytree.postorder;

import algorithm.tree.binarytree.base.TreeNode;
import algorithm.tree.binarytree.base.TreeNodeEvent;

import java.util.Stack;
import java.util.function.Consumer;

public class PostorderNonRecursion {
    public static void traverse(TreeNode node, Consumer<TreeNode> onVisit) {
        Stack<TreeNodeEvent<TreeNode>> nodeStack = new Stack<>();
        nodeStack.push(new TreeNodeEvent<>(0, node));
        while (!nodeStack.empty()) {
            TreeNodeEvent<TreeNode> event = nodeStack.pop();
            TreeNode temp = event.data();
            switch (event.type()) {
                case 0 -> {
                    if(temp!=null){
                        nodeStack.push(new TreeNodeEvent<>(1, temp));
                        nodeStack.push(new TreeNodeEvent<>(0, temp.getRight()));
                        nodeStack.push(new TreeNodeEvent<>(0, temp.getLeft()));
                    }
                }
                case 1 -> {
                    onVisit.accept(temp);
                }
            }
        }
    }
}
